package com.teacher.hong.servlet;

import com.alibaba.fastjson.JSONObject;
import com.teacher.hong.entity.User;
import com.teacher.hong.service.IUserService;
import com.teacher.hong.service.impl.UserServiceImpl;
import com.teacher.hong.utils.SecurityUtils;
import com.teacher.hong.utils.TokenUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 登录接口
 */
//@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    IUserService userService;

    @Override
    public void init() throws ServletException {
        //创建一个应用上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        userService = context.getBean("userService", UserServiceImpl.class);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //账号
        String account = req.getParameter("account");
        //密码
        String password = SecurityUtils.md5Encrypt(req.getParameter("password"));

//        boolean success = userService.login(new User(account, password));
//
//        JSONObject object = new JSONObject(true);
//        object.put("state", success ? 200 : 402);
//        object.put("message", success ? "登录成功" : "登录失败，账号或密码错误");
//        if (success) {
//            Date issuedTime = new Date();
//            Date expiresTime = new Date(issuedTime.getTime() + 1000 * 60 * 60 * 72);  //过期时间为72个小时
//            object.put("token", TokenUtils.generate(account, issuedTime, expiresTime));
//        }
//        object.put("timestamp", LocalDateTime.now());
//
//        resp.setStatus(success ? 200 : 402);
//
//        resp.setContentType("application/json;charset=utf-8");
//        resp.getWriter().write(object.toJSONString());

    }
}
